
const BlogModel = require("./models/BlogModel");
const blogTypeModel = require("./models/BlogTypeModel");
const { Op, and } = require("sequelize");
// 添加文章
module.exports.addBlog = async function (BlogInfos) {
    const result = await BlogModel.create(BlogInfos);
    return result ? result.toJSON() : result;
}

// 通过分页查询其文章
module.exports.getPageBlog = async function ({ page = 1, limit = 10, keyword = "", categoryId = "" }) {
    //如果其存在文章id则通过文章分类id进行查询
    if (categoryId) {
        const data = await BlogModel.findAndCountAll({
            where: {
                categoryId,
                [Op.or]: {
                    title: {
                        [Op.substring]: `${keyword}`
                    },
                    description: {
                        [Op.substring]: `${keyword}`
                    }

                }
            },
            include: [
                {
                    model: blogTypeModel,
                    as: "category",
                    where: {
                        id: categoryId
                    }
                }
            ],
            offset: (+page - 1) * (+limit),
            limit: +limit,

        })
        return JSON.parse(JSON.stringify(data));
    } else {
        const data = await BlogModel.findAndCountAll({
            offset: (+page - 1) * (+limit),
            limit: +limit,
            include: [
                {
                    model: blogTypeModel,
                    as: "category",
                }
            ],
            where: {
                [Op.or]: {
                    title: {
                        [Op.substring]: `${keyword}`
                    },
                    description: {
                        [Op.substring]: `${keyword}`
                    }

                }
            },

        })
        return JSON.parse(JSON.stringify(data))
    }
}

// 删除文章
module.exports.deleteBlog = async function (id) {
    const data = await BlogModel.destroy({
        where: {
            id
        }
    })

    return data;
}

// 修改文章
module.exports.updateBlog = async function (id, info) {
    console.log(id, 'updateId')
    await BlogModel.update(info, {
        where: {
            id
        }
    })
    const data = await BlogModel.findAndCountAll({
        include: [
            {
                model: blogTypeModel,
                as: "category",
            }
        ],
        where: {
            id
        }

    })
    return JSON.parse(JSON.stringify(data));
}

// 获取单篇文章
module.exports.getOneBlog = async function (id) {
    const data = await BlogModel.findByPk(id);
    return data ? data.toJSON() : data;
}

//获取分类下的所有文章数量
module.exports.getAllBlog = async function (categoryId) {
    return await BlogModel.count({
        where: {
            categoryId
        }
    })
}